// pages/biz/goods.js
const BizGoodsService = require('../../services/bizGoods');
const auth = require('../../utils/auth.js');
const bizPayService = require('../../services/bizPay.js');
Page({

    /**
     * 页面的初始数据
     */
    data: {
        id: 0,
        goods: null, // 商品详情
        buyPanelVisible: false,
        quantity: 1,
        isLoggedIn: false, // 登录状态
        userInfo: null, // 用户信息
        loginReady: false, // 登录是否准备完成
        comments: [], // 商品点评列表

        // 支付选择相关
        userScore: 0, // 用户云豆余额
        cardList: [], // 用户有效卡片列表
        cardListWithStatus: [], // 带选中状态的卡片列表
        selectedCards: [], // 选中的卡片列表
        showCardPanel: false, // 是否显示卡片选择面板
        totalCardScore: 0, // 总卡片云豆数量
        useCardScore: 0, // 使用的卡片云豆数量
        useScore: 0, // 使用的云豆数量
        remainMoney: 0, // 需要微信支付的金额
        recentOrders: [] // 最近商品订单记录
    },

    /**
     * 生命周期函数--监听页面加载
     */
    async onLoad(options) {
        if (!options.id) {
            wx.showToast({ title: '缺少商品ID', icon: 'none' });
            return;
        }

        this.data.id = options.id;

        // 检查登录状态
        await this.checkLoginStatus();

        // 加载商品详情
        await this.loadGoodsDetail();

        // 加载最近商品订单记录
        await this.loadRecentOrders();

        

        this.getGoodsPings();
    },

    /**
     * 检查登录状态
     */
    async checkLoginStatus() {
        try {
            const loginStatus = await auth.checkLoginStatus();
            this.setData({
                isLoggedIn: loginStatus.isLoggedIn,
                userInfo: loginStatus.userInfo,
                loginReady: true
            });
        } catch (error) {
            console.error('检查登录状态失败:', error);
            this.setData({ loginReady: true });
        }
    },

    /**
     * 加载用户云豆余额和卡片
     */
    async loadUserBalance() {
        try {
            // 加载云豆余额
            
            const balanceResult = await bizPayService.getBalance({
                biz_id: this.data.goods.biz_id
            });

            if (balanceResult.success) {
                this.setData({
                    userScore: balanceResult.data.score || 0
                });
            }

            // 加载用户有效卡片列表
            const cardService = require('../../services/card.js');
            const cardResult = await cardService.getValidCards({
                showLoading: false
            });

            if (cardResult.success) {
                const validCards = cardResult.data.list || [];
                const cardListWithStatus = validCards.map(card => ({
                    ...card,
                    isSelected: false
                }));

                // 计算总卡片云豆数量
                const totalCardScore = validCards.reduce((total, card) => {
                    return total + (card.card_score || card.score || 0);
                }, 0);

                this.setData({
                    cardList: validCards,
                    cardListWithStatus: cardListWithStatus,
                    totalCardScore: totalCardScore
                });
            }

            // 计算支付方案
            this.calculatePayPlan();
        } catch (error) {
            console.error('加载用户余额和卡片失败:', error);
        }
    },

    /**
     * 加载商品详情
     */
    async loadGoodsDetail() {
        try {
            const res = await BizGoodsService.getGoodsDetail(this.data.id);
            if (res.success) {
                this.setData({
                     goods: res.data 
                    },function(){
                        if (this.data.isLoggedIn) {
                            this.loadUserBalance();
                        }
                    });
            } else {
                wx.showToast({ title: res.msg || '加载失败', icon: 'none' });
            }
        } catch (e) {
            wx.showToast({ title: '网络错误', icon: 'none' });
        }
    },

    /**
     * 加载最近商品订单记录
     */
    async loadRecentOrders() {
        try {
            const res = await BizGoodsService.getRecentOrders(this.data.id);
            if (res.success) {
                this.setData({ recentOrders: res.data.list || [] });
            } else {
                wx.showToast({ title: res.msg || '加载失败', icon: 'none' });
            }
        } catch (e) {
            wx.showToast({ title: '网络错误', icon: 'none' });
        }
    },

    /**
     * 自动登录完成回调
     * 由app.js调用
     */
    onAutoLoginComplete(isLoggedIn, userInfo) {
        console.log('商品页面收到登录状态更新:', { isLoggedIn, userInfo });

        this.setData({
            isLoggedIn: isLoggedIn,
            userInfo: userInfo,
            loginReady: true
        });
    },

    onBuy() {
        // 检查登录状态
        if (!this.data.isLoggedIn) {
            wx.showToast({
                title: '请先登录',
                icon: 'none'
            });
            return;
        }

        this.setData({ buyPanelVisible: true });
    },

    goToBiz() {
        wx.navigateTo({ url: `/pages/biz/detail?id=${this.data.goods.biz_id}` });
    },

    // 开始购买
    async doBuy() {
        // 再次检查登录状态
        if (!this.data.isLoggedIn) {
            wx.showToast({
                title: '登录状态异常，请重新登录',
                icon: 'none'
            });
            return;
        }

        try {
            // 准备支付数据
            // 计算每个选中卡片的实际使用云豆数量
            const selectedCardsWithUseScore = this.data.selectedCards.map(card => {
                // 按卡片云豆数量从高到低排序，优先使用云豆多的卡片
                const sortedCards = [...this.data.selectedCards].sort((a, b) => {
                    const scoreA = a.card_score || a.score || 0;
                    const scoreB = b.card_score || b.score || 0;
                    return scoreB - scoreA;
                });
                let remainingPayMoney = this.data.goods ? this.data.goods.price * this.data.quantity : 0;
                let actualUseScore = 0;
                for (const selectedCard of sortedCards) {
                    const cardScore = selectedCard.card_score || selectedCard.score || 0;
                    if (selectedCard.id === card.id) {
                        if (cardScore > 0 && remainingPayMoney > 0) {
                            actualUseScore = Math.min(cardScore, remainingPayMoney);
                        }
                        break;
                    } else {
                        if (cardScore > 0 && remainingPayMoney > 0) {
                            const useOtherCardScore = Math.min(cardScore, remainingPayMoney);
                            remainingPayMoney -= useOtherCardScore;
                        }
                    }
                }
                return {
                    card_id: card.id,
                    card_name: card.card_name || card.name || '',
                    card_score: card.card_score || card.score || 0,
                    use_score: actualUseScore
                };
            });

            const payData = {
                id: this.data.id,
                quantity: this.data.quantity,
                // 云豆余额相关数据
                use_score: this.data.useScore,
                // 福利卡相关数据
                use_card_score: this.data.useCardScore,
                selected_cards: selectedCardsWithUseScore
            };


            const res = await BizGoodsService.buyGoods(payData);

            if (res.success) {
                // 判断是否需要微信支付
                if (this.data.remainMoney > 0) {
                    // 需要微信支付
                    wx.requestPayment({
                        'timeStamp': res.data.config.timeStamp,
                        'nonceStr': res.data.config.nonceStr,
                        'package': res.data.config.package,
                        'signType': 'MD5',
                        'paySign': res.data.config.paySign,
                        'success': (r) => {
                            if (r.errMsg == 'requestPayment:ok') {
                                wx.showToast({ title: '支付成功', icon: 'success' });
                                this.setData({ buyPanelVisible: false });

                                setTimeout(() => {
                                    wx.navigateTo({
                                        url: '/pages/i/order-detail?order_id=' + res.data.order_id
                                    });
                                }, 1000);
                            }
                        },
                        'fail': (r) => {
                            wx.showToast({ title: '支付失败', icon: 'none' });
                        }
                    });
                } else {
                    // 无需微信支付，直接成功
                    wx.showToast({ title: '购买成功', icon: 'success' });
                    this.setData({ buyPanelVisible: false });

                    setTimeout(() => {
                        wx.navigateTo({
                            url: '/pages/i/order-detail?order_id=' + res.data.order_id
                        });
                    }, 1000);
                }
            } else {
                wx.showToast({ title: res.message || '购买失败', icon: 'none' });
            }
        } catch (error) {
            console.error('购买失败:', error);
            wx.showToast({ title: '购买失败，请重试', icon: 'none' });
        }
    },

    onChange(event) {
        this.setData({ quantity: event.detail });
        // 重新计算支付方案
        this.calculatePayPlan();
    },

    onClose() {
        this.setData({ buyPanelVisible: false });
    },

    /**
     * 生命周期函数--监听页面初次渲染完成
     */
    onReady() {

    },

    /**
     * 生命周期函数--监听页面显示
     */
    onShow() {
        // 页面显示时检查登录状态
        if (this.data.loginReady) {
            this.checkLoginStatus();
        }

        // 如果已登录，重新加载用户余额和卡片
        if (this.data.isLoggedIn) {
            this.loadUserBalance();
        }
    },

    /**
     * 生命周期函数--监听页面隐藏
     */
    onHide() {

    },

    /**
     * 生命周期函数--监听页面卸载
     */
    onUnload() {

    },

    /**
     * 页面相关事件处理函数--监听用户下拉动作
     */
    onPullDownRefresh() {

    },

    /**
     * 页面上拉触底事件的处理函数
     */
    onReachBottom() {

    },

    /**
     * 用户点击右上角分享
     */
    onShareAppMessage() {

    },

    /**
     * 切换卡片选择面板
     */
    toggleCardPanel() {
        this.setData({
            showCardPanel: !this.data.showCardPanel
        });
    },

    /**
     * 选择/取消选择卡片
     */
    onCardSelect(e) {
        const cardId = e.currentTarget.dataset.id;
        const card = this.data.cardList.find(item => item.id == cardId);

        if (card) {
            const selectedCards = [...this.data.selectedCards];
            const existingIndex = selectedCards.findIndex(item => item.id == cardId);

            if (existingIndex > -1) {
                // 如果已选中，则取消选择
                selectedCards.splice(existingIndex, 1);
            } else {
                // 如果未选中，检查是否可以添加新卡片
                // 计算当前已选择卡片的云豆总量
                let currentTotalCardScore = 0;
                for (const selectedCard of selectedCards) {
                    const cardScore = selectedCard.card_score || selectedCard.score || 0;
                    currentTotalCardScore += cardScore;
                }

                // 计算总支付金额
                const totalPrice = this.data.goods ? this.data.goods.price * this.data.quantity : 0;

                // 如果当前已选择的卡片云豆已经足够支付，则不允许再选择其他卡片
                if (currentTotalCardScore >= totalPrice) {
                    wx.showToast({
                        title: '已选择的卡片云豆足够支付，请先取消选择',
                        icon: 'none',
                        duration: 2000
                    });
                    return;
                }

                // 可以添加新卡片
                selectedCards.push(card);
            }

            // 更新卡片列表的选中状态
            const cardListWithStatus = this.data.cardListWithStatus.map(item => ({
                ...item,
                isSelected: selectedCards.some(selectedCard => selectedCard.id === item.id)
            }));

            this.setData({
                selectedCards: selectedCards,
                cardListWithStatus: cardListWithStatus
            });

            // 重新计算支付方案
            this.calculatePayPlan();
        }
    },

    /**
     * 取消选择所有卡片
     */
    onCardDeselect() {
        // 更新卡片列表的选中状态
        const cardListWithStatus = this.data.cardListWithStatus.map(item => ({
            ...item,
            isSelected: false
        }));

        this.setData({
            selectedCards: [],
            useCardScore: 0,
            cardListWithStatus: cardListWithStatus
        });

        // 重新计算支付方案
        this.calculatePayPlan();
    },

    /**
     * 计算支付方案
     */
    calculatePayPlan() {
        const { goods, quantity, userScore, selectedCards } = this.data;

        if (!goods || !quantity) return;

        const totalPrice = goods.price * quantity;
        let totalUseScore = 0;
        let totalCardScore = 0;
        let useScore = 0;

        // 1. 先计算用户选择的卡片云豆使用量（多选）
        if (selectedCards.length > 0) {
            let remainingPayMoney = totalPrice;

            // 按卡片云豆数量从高到低排序，优先使用云豆多的卡片
            const sortedCards = [...selectedCards].sort((a, b) => {
                const scoreA = a.card_score || a.score || 0;
                const scoreB = b.card_score || b.score || 0;
                return scoreB - scoreA;
            });

            for (const card of sortedCards) {
                const cardScore = card.card_score || card.score || 0;
                if (cardScore > 0 && remainingPayMoney > 0) {
                    const useCardScore = Math.min(cardScore, remainingPayMoney); // 支持小数
                    totalCardScore += useCardScore;
                    totalUseScore += useCardScore;
                    remainingPayMoney -= useCardScore;
                }
            }
        }

        // 2. 然后自动计算云豆使用量（补足剩余金额）
        const remainingMoney = totalPrice - totalUseScore;
        if (remainingMoney > 0) {
            const needScore = remainingMoney; // 每个云豆代表1元，支持小数
            useScore = Math.min(userScore, needScore); // 使用的云豆数量
            totalUseScore += useScore;
        }

        // 3. 最后计算微信支付补差价
        const remainMoney = (totalPrice - totalUseScore).toFixed(2); // 需要微信支付的金额

        this.setData({
            useScore: useScore,
            useCardScore: totalCardScore,
            remainMoney: remainMoney
        });

        console.log('支付计算详情:', {
            totalPrice: totalPrice,
            totalUseScore: totalUseScore,
            useScore: useScore,
            totalCardScore: totalCardScore,
            remainMoney: remainMoney,
            selectedCards: selectedCards.map(card => ({
                card_id: card.id,
                card_name: card.card_name || card.name || '',
                card_score: card.card_score || card.score || 0
            }))
        });
    },

    async getGoodsPings() {
        const { id } = this.data;
        try {
            const result = await BizGoodsService.goodsPings({
                id: id,
                showLoading: true
            });

            this.setData({
                comments: result.data.list || []
            });
        } catch (error) {
            console.error('获取商品点评列表失败:', error);
        }
    },

    toComments() {
        wx.navigateTo({ url: `/pages/biz/goods-comments?id=${this.data.id}` });
    },

    previewImage(e) {
        const { current, urls } = e.currentTarget.dataset;
        wx.previewImage({
            current: current,
            urls: urls
        });
    }
})